package site.liuming.truismcms.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import site.liuming.truismcms.core.common.UnifyResponse;
import site.liuming.truismcms.core.common.UnifyResponseFactory;
import site.liuming.truismcms.exceptions.ParameterException;
import site.liuming.truismcms.utils.StringUtil;
import site.liuming.truismcms.vo.UploadImgVo;
import site.liuming.truismcms.web.service.ImgUploadService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 图片上传下载控制器
 */
@RequestMapping("/img")
@RestController
public class ImgController {

    @Autowired
    private ImgUploadService imgUploadService;

    @PostMapping("/upload")
    public UnifyResponse<UploadImgVo> uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        if (Objects.isNull(file)) {
            throw new ParameterException(6002);
        }
        FileInputStream inputStream = (FileInputStream) file.getInputStream();
        String url = imgUploadService.uploadImg(inputStream, StringUtil.getRandomImgName(file.getOriginalFilename()));
        return UnifyResponseFactory.success(new UploadImgVo(url));
    }

}
